<?php


namespace app\controller\admin;


use app\BaseController;
use app\common\Consts;
use app\models\log\AdminLogModel;
use app\services\log\AdminLogService;
use think\facade\Db;


class LogController extends BaseController
{
    public function getList()
    {
        try {
            $where = [];
            $search = $this->request->param('search', '', 'trim');
            if ($search) {
                $where[] = ['user_name|link|params', 'like', '%' . $search . '%'];
            }
            $method = $this->request->param('method', '', 'trim');
            if ($method) {
                $where[] = ['type', '=', $method];
            }
            $ip = $this->request->param('ip', '', 'trim');
            if ($ip) {
                $where[] = ['ip', '=', $ip];
            }
            $startTime = $this->request->param('start_time', '', 'trim');
            if ($startTime) {
                $where[] = ['create_time', '>=', strtotime($startTime)];
            }
            $endTime = $this->request->param('end_time', '', 'trim');
            if ($endTime) {
                $where[] = ['create_time', '<=', strtotime($endTime)];
            }
            $order = $this->request->param('field', 'id');
            $orderBy = $this->request->param('order', 'desc');
            $list = AdminLogModel::where($where)
                ->order($order, $orderBy)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function clearLog()
    {
        try {
            $userInfo = $this->request->userInfo;
            $roleId = $userInfo->role_id;
            if ($roleId != Consts::ADMIN_ROLE_ID && $roleId != Consts::MANAGER_ROLE_ID) {
                throw new \Exception('请登陆管理员账号操作！');
            }
            $startTime = $this->request->param('start_time', '', 'trim');
            $endTime = $this->request->param('end_time', '', 'trim');
            if ($startTime && $endTime) {
                AdminLogModel::where('create_time', 'between', [strtotime($startTime), strtotime($endTime)])->delete();
            } else {
                Db::execute('truncate table mp_admin_log');
            }
            AdminLogService::createLog($userInfo->id,
                $userInfo->username,
                $this->request->domain(true),
                $this->request->pathinfo(),
                $this->request->param(),
                $this->request->method(),
                $this->request->ip(),
                $this->request->header('user-agent'),
                $this->request->header('token'),
                '清除日志'
            );
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}